<template>
  <div>
    <div class="content">
      <!-- <el-breadcrumb class="title">
        <el-breadcrumb-item>账号管理</el-breadcrumb-item>
      </el-breadcrumb> -->
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="accountmanage.formInline" ref="formInline" class="demo-form-inline">
        <el-form-item label="" prop="fullName">
          <el-input v-model="accountmanage.formInline.fullName" placeholder="姓名/手机号"></el-input>
        </el-form-item>
        <el-form-item label="" prop="areaId">
          <el-cascader v-model="accountmanage.formInline.areaId" placeholder="所属市/区" :options="accountmanage.options"
            :props="accountmanage.optionProps"></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit()">查询</el-button>
          <el-button @click="resetForm('formInline')" style="margin-right: 10px">重置</el-button>
        </el-form-item>
      </el-form>

      <el-button @click="inducts('ruleForm')" style="margin-right: 10px">新建账号</el-button>

      <!-- <a href="http://10.31.0.86:8080/api/manage/admin/export"><el-button>导出数据</el-button></a> -->
      <!-- <a href="http://43.136.116.70:8080/api/questionBank/export"><el-button>导出数据</el-button></a>     -->
      <el-button @click="exportExcel">导出数据</el-button>
    </div>
    <!-- main表格-->
    <el-table :data="accountmanage.tableData" border style="width: 100%; margin-top: 15px" :header-cell-style="{
      background: '#f0f7fe',
      color: '#467ee1',
      fontSize: '16px',
    }">
      <el-table-column label="序号" align="center" width="100" type="i">
        <template slot-scope="{ $index }">
          {{ accountmanage.serachindex + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="fullName" label="姓名" align="center" min-width="10%">
      </el-table-column>
      <el-table-column prop="username" label="账号" align="center" min-width="20%">
      </el-table-column>
      <el-table-column prop="areaName" label="所属市/区" align="center" min-width="20%">
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center" min-width="30%"> 
      </el-table-column>
      <el-table-column prop="roles" label="所属角色" align="center" min-width="50%">
        <template slot-scope="scope">
          {{
            scope.row.roles
            ? scope.row.roles.map((item) => (item ? item.name : "")).join("/")
            : ""
          }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center" class="statue" min-width="20%">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
            @change="changeSwitch(scope.row, $event)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" :formatter="formatDate" min-width="50%">
      </el-table-column>
      <el-table-column prop="action" label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="inducts2(scope.$index, scope.row)">编辑</el-button>
          <!-- <el-button
              size="mini"
              type="danger"
              @click="HandleDeletes(scope.$index, scope.row)"
              >删除</el-button
            > -->
          <el-button size="mini" type="danger" @click="PasswordDeletes(scope.$index, scope.row)">修改密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 30, 40]"
        :page-size="accountmanage.pagination.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="accountmanage.pagination.total">
      </el-pagination>
    </div>
    <!-- 弹出框 -->
    <el-dialog title="新增/修改账号" :visible.sync="accountmanage.dialogVisible" width="40%" :destory-on-close="true"
      @close="disaa()">
      <el-form ref="ruleForm" :rules="accountmanage.dialogrules" :model="accountmanage.form" class="form-item">
        <el-form-item prop="fullName" label="姓名:" :label-width="accountmanage.formLabelWidth">
          <el-input id="fullName" v-model="accountmanage.form.fullName"></el-input>
        </el-form-item>
        <el-form-item prop="areaId" label="所属市区:" :label-width="accountmanage.formLabelWidth">
          <el-cascader ref="cascaders" v-model="accountmanage.form.areaId" :options="accountmanage.options"
            :props="accountmanage.optionProps" @change="handleChange('cascaders')"></el-cascader>
        </el-form-item>
        <el-form-item prop="phone" label="电话号码:" :label-width="accountmanage.formLabelWidth">
          <el-input id="phone" v-model="accountmanage.form.phone"></el-input>
        </el-form-item>

        <el-form-item prop="roles" label="角色:" :label-width="accountmanage.formLabelWidth">
          <el-select id="roles" v-model="accountmanage.form.roles" multiple placeholder="请选择角色">
            <el-option v-for="item in accountmanage.role" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="username" label="账号:" :label-width="accountmanage.formLabelWidth"
          v-if="accountmanage.passshow">
          <el-input id="username" v-model="accountmanage.form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码:" :label-width="accountmanage.formLabelWidth"
          v-if="accountmanage.passshow">
          <el-input id="password" v-model="accountmanage.form.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogcancle('ruleForm')">取 消</el-button>
        <!-- <el-button type="primary" @click="download()" v-loading.fullscreen.lock="fullscreenLoading">保存</el-button> -->
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </span>
    </el-dialog>
    <!-- //修改密码弹出框 -->
    <el-dialog title="新增/修改账号" :visible.sync="accountmanage.dialogVisible2" width="40%" @close="disaa2()"
      :destory-on-close="true">
      <el-form ref="ruleForm2" :model="accountmanage.formPass" class="form-item">
        <el-form-item prop="password" label="密码:" :label-width="accountmanage.formLabelWidth">
          <el-input v-model="accountmanage.formPass.password"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <!-- 与新增账号的取消公用一个点击事件 -->
        <el-button @click="dialogcancle('ruleForm2')">取 消</el-button>
        <el-button type="primary" @click="submitpass()">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from "@/utls/format";

import {
  AccountSerach,
  GetAdmin,
  SaveAdmin,
  UpdateAdmin,
  ExportAdmin,
  DeleteAdmin,
  updateStatus,
  getRoleSelections,
} from "@/api/AccountManage";

export default {
  data() {
    //校验电话号码
    var validatePass = (rule, value, callback) => {
      let num = /^1[3456789]\d{9}$/;
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else {
        if (!num.test(value)) {
          callback(new Error("请输入正确的电话号码"));
        }
        callback();
      }
    };
    return {
      formatDate,
      accountmanage: {
        //级联选择器配置
        optionProps: {
          value: "id",
          label: "areaName",
          children: "children",
          // expandTrigger: "hover",
          checkStrictly: true, // 可选择任意一级
        },
        // optionsfrom: [],//搜索表单的级联选择器
        options: [], //修改、新建表单的级联选择器

        //校验表单
        dialogrules: {
          fullName: [
            { required: true, message: "请输入您的姓名", trigger: "blur" },
          ],
          areaId: [
            { required: true, message: "请选择所属市区", trigger: "change" },
          ],
          roles: [{ required: true, message: "请选择角色", trigger: "blur" }],
          phone: [
            {
              validator: validatePass,
              trigger: "blur",
              required: true,
            },
          ],
          username: [
            { required: true, message: "请输入您的账户", trigger: "blur" },
          ],
          password: [
            { required: true, message: "请输入您的密码", trigger: "blur" },
          ],
        },
        //分页属性
        serachindex: 0,
        pagination: {
          currentPage: 1,
          pagesize: 10,
          size: "",
          total: 0,
        },
        //弹出框表单
        form: {
          fullName: "",
          areaId: "",
          phone: "",
          username: "",
          password: "",
          roles: [],
        },
        formLabelWidth: "100px", //弹出框表单的lable宽度
        dialogVisible: false, //弹出框的值
        dialogVisible2: false, //弹出框的值

        formInline: {
          //搜索表单
          fullName: "",
          areaId: "",
        },
        TableIndex: "", //编辑行索引
        TableRow: "", //编辑行信息，与编辑密码公用一个row存储

        //main展示表单信息
        tableData: [],
        role: [], //多个角色展示的中间变量
        passshow: true, //是否展示账号密码选项
        areaId: "",
        formPass: {
          password: "",
        }, //修改密码弹出框存储
      },
    };
  },

  methods: {
    //获取页面表格数据
    async getData(pageSize, pageNum) {
      await GetAdmin({
        pageSize,
        pageNum,
      }).then((res) => {
        this.accountmanage.tableData = res.data.data.list;
        console.log(this.accountmanage.tableData);
        this.accountmanage.pagination.total = res.data.data.total;
      });
    },
    //导出数据
    async exportExcel() {
      const res = await ExportAdmin();
      let content = res.data;
      let data = new Blob([content], {
        type: "application/vnd.ms-excel",
      });
      let downloadUrl = window.URL.createObjectURL(data);
      var a = document.createElement("a");
      document.body.appendChild(a);
      a.href = downloadUrl;
      a.download = "账户信息";
      a.click();
      window.URL.revokeObjectURL(downloadUrl);
    },
    // 更新页面数据接口
    async updateData(id, password) {
      await updateStatus({
        id,
        password,
      }).then((res) => {
        this.accountmanage.dialogVisible2 = false;
        this.$message.success(res.data.message);
      });
    },
    //switch本行的值
    changeSwitch(row, eve) {
      updateStatus({ id: row.id, status: eve }).then((res) => { });
    },
    //级联选择改变触发该事件
    handleChange(val) {
      this.accountmanage.areaId = this.$refs[val].getCheckedNodes()[0].value;
    },
    //点击弹出框的退出图标清空弹出框表单内容
    disaa() {
      this.dialogcancle("ruleForm");
      this.clearform();
    },
    disaa2() {
      this.dialogcancle("ruleForm2");
    },
    // 清空弹出框表单内容
    dialogcancle(formName) {
      this.accountmanage.dialogVisible = false;
      this.accountmanage.dialogVisible2 = false;
      this.$refs[formName].resetFields(); //清除表单验证
    },
    //改变每页条数
    handleSizeChange(value) {
      this.accountmanage.pagination.pagesize = value;
      this.getData(value, this.accountmanage.pagination.currentPage);
    },
    //改变当前页触发
    handleCurrentChange(value) {
      this.accountmanage.pagination.currentPage = value;
      this.accountmanage.serachindex =
        (value - 1) * this.accountmanage.pagination.pagesize;
      this.getData(this.accountmanage.pagination.pagesize, value);
    },
    //表单修改密码提交事件
    submitpass() {
      //传password和id两个参数
      this.updateData(
        this.accountmanage.TableRow.id,
        this.accountmanage.formPass.password
      );
    },

    //表单保存修改
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        this.accountmanage.form.areaId = this.accountmanage.areaId;
        if (valid) {
          //校验通过走这里
          // 如果tablerow参数有值则执行以下代码,说明点击的是修改
          if (this.accountmanage.TableRow != "") {
            UpdateAdmin({
              id: this.accountmanage.TableRow.id,
              fullName: this.accountmanage.form.fullName,
              areaId: this.accountmanage.form.areaId,
              phone: this.accountmanage.form.phone,
              roles: this.accountmanage.form.roles,
            }).then((res) => {
              this.getData(
                this.accountmanage.pagination.pagesize,
                this.accountmanage.pagination.currentPage
              );
              this.accountmanage.dialogVisible = false;
              this.$message.success(res.data.message);
            });
          } else {
            SaveAdmin(this.accountmanage.form).then((res) => {
              if (res.data.status == 1000) {
                // console.log(res.data.message);
                this.$message.error(res.data.message);
              } else {
                GetAdmin({
                  pageNum: this.accountmanage.pagination.currentPage,
                  pageSize: this.accountmanage.pagination.pagesize,
                }).then((res) => {
                  this.accountmanage.tableData = res.data.data.list;
                  this.accountmanage.pagination.total = res.data.data.total;
                  this.accountmanage.dialogVisible = false;
                  this.$message.success(res.data.message);
                });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    PasswordDeletes(index, row) {
      this.accountmanage.dialogVisible2 = true;
      this.accountmanage.TableRow = row;
    },
    //搜索重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
      //获取数据不传参数
      this.getData(10, 1);
    },
    clearform() {
      this.accountmanage.form.areaId = "";
      this.accountmanage.form.fullName = "";
      this.accountmanage.form.phone = "";
      this.accountmanage.form.roles = [];
      this.accountmanage.form.username = "";
      this.accountmanage.form.password = "";
    },
    //打开弹出框
    inducts(val) {
      this.accountmanage.dialogVisible = true;
      this.accountmanage.passshow = true;

      this.accountmanage.TableRow = "";
      // console.log(val, 4545);
      // this.dialogcancle("ruleForm");
      // this.$refs.ruleForm.resetFields();
      // this.$refs[val].resetField()
      // this.$refs.formData.resetFields()
      this.clearform();
    },

    inducts2(index, row) {
      this.accountmanage.dialogVisible = true;
      this.accountmanage.passshow = false;
      //传入数据给form
      this.accountmanage.TableRow = row;
      // console.log(row, 4444);
      // if()
      // console.log(row, 4444);
      // if()
      this.accountmanage.form.roles = row.roles.map((item) => {
        return item.id;
      });
      this.accountmanage.form.fullName = row.fullName;
      this.accountmanage.form.areaId = row.areaId;
      this.accountmanage.form.phone = row.phone;
    },
    // // 查询信息
    onSubmit() {
      GetAdmin({
        keyWord: this.accountmanage.formInline.fullName,
        areaId:
          this.accountmanage.formInline.areaId[
          this.accountmanage.formInline.areaId.length - 1
          ],
      }).then((res) => {
        this.accountmanage.tableData = res.data.data.list;
        this.accountmanage.pagination.total = res.data.data.total;
      });
    },
  },
  mounted() {
    getRoleSelections()
      .then((res) => {
        res.data.data.forEach((item) => {
          this.accountmanage.role.push(item);
        });
      })
      .catch((err) => { });
    // 获取表格信息,角色字符串拼接
    this.getData(10, 1);

    AccountSerach(0).then((res) => {
      this.accountmanage.options = res.data.data;
    });
  },
};
</script>
<style scoped>
.content {
  padding-top: 20px;
}

.el-pagination {
  margin: 25px 0;
}

.form-item .el-form-item {
  width: 80%;
}

.form-item .el-select {
  width: 100%;
}

.form-item .el-cascader {
  width: 100%;
}

.status {
  text-align: center;
}

.title {
  height: 50px;
  line-height: 50px;
  background-color: #f9f9f9;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
  font-size: 17px;
  font-weight: bolder;
  padding: 0 20px;
  margin-bottom: 20px;
}

:deep(.el-pager li.active) {
  color: #ffffff;
  background-color: #409eff;
}

:deep(.el-pager li:hover) {
  color: #787d83;
}
</style>
